<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>stock</title>
  <link rel="Shortcut Icon" href="favicon.ico">
  <!-- Bootstrap -->
  <link rel="stylesheet" href="bootstrap@5.1.0_dist_bootstrap.min.css">
  <script src="jquery@3.5.1_dist_jquery.min.js"></script>
  <script src="bootstrap@5.1.0_dist_js_bootstrap.bundle.min.js"></script>
  <script src="chart.js"></script>

  </script>
  <script type="text/javascript">
    $(document).ready(function () {
      let t = 10000
      countDown(t)
      // initChart()
      init();
      setInterval("init()", t);
      $('#dropdownMenu li a').on('click', function () {
        $('#dropdownMenuButton1').text($(this).html())
        getLimitUp();
      });
      $(".select").change(function (e) {
        getBubble();
      });
    });

    function countDown(t) {
      let time = t / 1000
      var time1 = setInterval(function () {
        if (time == 0) {
          time = t / 1000 - 1;
        } else {
          time--;
        }
        $("#timer").html(time);
      }, 1000);

    }

    function init() {
      getLimitUp();
      getBubble();
      getZhiShu();
      getTopInfo();
      getYesterdayLimitUp();
      getTemperature();
      getBrokenRatio();
      // getPcp();
    }

    function initChart() {
      const ctx = document.getElementById('myChart');
      new Chart(ctx, {
        type: 'bar',
        data: {
          labels: ['涨停', '+10%', '8%', '+6%', '+4%', '2%', '0%', '-2%', '-4%', '-6%', '-8%', '-10%', '跌停'],
          datasets: [{
            data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            borderWidth: 1
          }]
        },
        options: {
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });
    }

    //涨跌分布
    function getPcp() {
      $.get(
        'https://flash-api.xuangubao.cn/api/market_indicator/pcp_distribution',
        function (res, status) {
          console.log(res.data)
          let udJson = res.data
          //labels:  ['涨停','+10%','8%','+6%','+4%','2%','0%','-2%','-4%','-6%','-8%','-10%','跌停'],
          let values = []
          values[0] = udJson['limit_up_count']
          values[1] = udJson['20']+udJson['10']
          values[2] = udJson['up_8']
          values[3] = udJson['up_6']
          values[4] = udJson['up_4']
          values[5] = udJson['up_2']
          values[6] = udJson['0']
          values[7] = udJson['down_2']
          values[8] = udJson['down_4']
          values[9] = udJson['down_6']
          values[10] = udJson['down_8']
          values[11] = udJson['down_10']
          values[12] = udJson['limit_down_count']
          const myChart = document.getElementById('myChart');
          // myChart.data.labels=Object.keys(data);
          myChart.data.datasets[0].data = values;
          myChart.update();
        })
    }

    //市场热度
    function getTemperature() {
      $.get('https://flash-api.xuangubao.cn/api/market_indicator/line?fields=market_temperature', function (res,
        status) {
        
        $('#redu')[0].innerHTML='市场热度：'+res.data[0].market_temperature.toFixed(2)
      })
    }

    //炸板率
    function getBrokenRatio() {
      $.get(
        'https://flash-api.xuangubao.cn/api/market_indicator/line?fields=limit_up_broken_count,limit_up_broken_ratio',
        function (res, status) {
          let list = res.data
          
          $('#zhaban')[0].innerHTML='炸板率：'+list[list.length - 1].limit_up_broken_ratio.toFixed(2)
        })
    }

    //昨日涨停表现
    function getYesPcp() {
      $.get('https://flash-api.xuangubao.cn/api/market_indicator/line?fields=yesterday_limit_up_avg_pcp', function (res,
        status) {
        let list = res.data
        console.log(list[list.length - 1].limit_up_broken_ratio)
      })
    }

    //今日大盘异动
    function getTodayYiDong() {
      $.get('https://api.xuangubao.cn/api/messages/todayDaPanYiDong?headmark=0', function (res, status) {
        console.log(res.data.data)
      })
    }
    //涨速板块
    function getZhangsuBK() {
      $.get('https://flash-api.xuangubao.cn/api/plate/incdec?move_type=1&limit=3', function (res, status) {
        console.log(res.data.data)
      })
    }
    //https://api.xuangubao.cn/api/pc/msgs?subjids=9,10,723,35,469,821&limit=30   7x24小时直播
    //https://flash-api.xuangubao.cn/api/pool/detail?pool_name=limit_up
    //https://flash-api.xuangubao.cn/api/stage2/plate/top_info?count=9&fields=all 
    function getBubble() {
      let lb = $("#lbSelect").find("option:selected").text();
      let zs = $("#zsSelect").find("option:selected").text();
      let hs = $("#hsSelect").find("option:selected").text();
      $.get('https://flash-api.xuangubao.cn/api/pool/bubble', function (res, status) {
        let result = res.data.sort(compare("change_percent"));
        result = $.grep(result, function (b) {
          //涨速大于2,涨幅大于0,量比大于2,换手大于2,非新股
          return b.mtm >= (zs / 100) && b.change_percent > 0 && b.volume_bias_ratio >= lb && (b.stock_type ==
            0 || b.stock_type == 4) && b.turnover_ratio >= (hs / 100)
        });
        $("#J_TbData").empty();
        for (var i = 0; i < result.length; i++) {
          //动态创建一个tr行标签,并且转换成jQuery对象
          var $trTemp = $("<tr></tr>");

          //往行里面追加 td单元格
          $trTemp.append("<td style='cursor:pointer' class='text-primary' onclick=\"getDetail('" + result[i]
            .symbol + "','" + result[i]
            .stock_chi_name + "')\"\>" + result[
              i].stock_chi_name + "</td>");
          $trTemp.append("<td style='cursor:pointer' class='text-primary' onclick=\"forwordGu('" + result[i]
            .symbol + "')\"\>" + result[
              i].symbol + "</td>");
          $trTemp.append("<td>" + (result[i].volume_bias_ratio).toFixed(2) + "</td>");
          $trTemp.append("<td>" + (result[i].mtm * 100).toFixed(2) + "</td>");
          $trTemp.append("<td>" + (result[i].turnover_ratio * 100).toFixed(2) + "%</td>");
          let color = result[i].change_percent > 0.06 ? 'text-danger' : ''
          $trTemp.append("<td class='" + color + "'>" + (result[i].change_percent * 100).toFixed(2) + "%</td>");
          $trTemp.append("<td>" + formatDateTime(result[i].first_limit_up) + "</td>");

          if (result[i].limit_up_days > 0) {
            $trTemp.append("<td class='text-danger'>" + result[i].limit_up_days + "</td>");
          } else {
            $trTemp.append("<td ></td>");
          }

          if (result[i].break_limit_up_times > 0) {
            $trTemp.append("<td class='text-danger'>" + result[i].break_limit_up_times + "</td>");
          } else {
            $trTemp.append("<td ></td>");
          }

          $trTemp.appendTo("#J_TbData");
        }
      });
    }

    function forwordZhi(id) {
      let url = 'https://xuangubao.cn/stock/' + id
      window.open(url)
    }

    function forwordBk(plate_id) {
      let url = 'https://xuangubao.cn/theme/' + plate_id
      window.open(url)
    }

    function forwordGu(id) {
      let url = 'https://xuangubao.cn/stock/' + id
      window.open(url)
    }

    //领涨跌板块
    function getTopInfo() {
      $.get('https://flash-api.xuangubao.cn/api/stage2/plate/top_info?count=5&fields=all', function (res, status) {
        let top = res.data.top_plate_info;
        let bottom = res.data.bottom_plate_info;
        $("#topdata").empty();
        for (var i = 0; i < top.length; i++) {
          let str = '<button onclick=\'forwordBk("' + top[i].plate_id +
            '")\' class="btn btn-danger" type="button">' + top[i].plate_name +
            ' <span class="badge">' + (top[i].core_avg_pcp * 100).toFixed(2) + '%</span></button>';
          $('#topdata').append(str);
        }
        for (var i = 0; i < bottom.length; i++) {
          let str = '<button onclick=\'forwordBk("' + bottom[i].plate_id +
            '")\' class="btn btn-success" type="button">' + bottom[i].plate_name +
            ' <span class="badge">' + (bottom[i].core_avg_pcp * 100).toFixed(2) + '%</span></button>';
          $('#topdata').append(str);
        }
      });
    }
    //昨日涨停
    function getYesterdayLimitUp() {
      $.get('https://flash-api.xuangubao.cn/api/pool/detail?pool_name=yesterday_limit_up', function (res, status) {
        let result = $.grep(res.data, function (b) {
          return b.yesterday_limit_up_days > 1 && (b.stock_type == 0 || b.stock_type == 4)
        });
        result = result.sort(compare("yesterday_limit_up_days"));
        let orderType = [{
          key: 'yesterday_limit_up_days', //按照哪个字段进行排序
          method: 'des' //标明按照什么方法
        }, {
          key: 'change_percent',
          method: 'des'
        }]
        result = objectSort(result, orderType)
        $("#yesterdayLimitUp").empty();
        for (var i = 0; i < result.length; i++) {
          var $trTemp = $("<tr></tr>");

          //往行里面追加 td单元格
          $trTemp.append("<td class='align-middle text-center table-danger'>" + result[i].yesterday_limit_up_days +
            "</td>");
          if (result[i].surge_reason != null) {
            $trTemp.append("<td class='text-primary' title='" + result[i].surge_reason.stock_reason +
              "' style='cursor:pointer' onclick=\"forwordBk('" + result[i]
              .surge_reason.related_plates[0].plate_id +
              "')\"\>" + result[i].surge_reason
              .related_plates[0]
              .plate_name +
              "</td>");

          } else {
            $trTemp.append("<td ></td>");
          }
          $trTemp.append("<td style='cursor:pointer' class='text-primary' onclick=\"forwordGu('" + result[i]
            .symbol + "')\"\>" +
            result[i].stock_chi_name + "</td>");
          let color = result[i].change_percent > 0 ? 'text-danger' : 'text-success'
          $trTemp.append("<td class='" + color + "'>" + (result[i].change_percent * 100).toFixed(2) + "%</td>");
          $trTemp.appendTo("#yesterdayLimitUp");

          table_rowspan("#yesterdayLimitUp", 1);
        }

      });
    }
    //对数组进行排序
    function compare(property) {
      return (firstobj, secondobj) => {
        const firstValue = firstobj[property];
        const secondValue = secondobj[property];
        return secondValue - firstValue; //降序
      };
    }

    function objectSort(arr, fields) {
      let checkOrder = (left, right, fields) => {
        let field = fields.shift()
        if (field === undefined) return 0;
        if (field.method == 'asc' && field.type == 'zh') {
          return left[field.key].localeCompare(right[field.key], 'zh-CN')
        } else if (field.method == 'asc') { //升序
          return left[field.key] === right[field.key] ? checkOrder(left, right, fields) : (left[field.key] < right[
            field.key] ? -1 : 1)
        } else if (field.method == 'des') {
          return left[field.key] === right[field.key] ? checkOrder(left, right, fields) : (left[field.key] > right[
            field.key] ? -1 : 1)
        }

      }
      return arr.sort((left, right) => {
        return checkOrder(left, right, JSON.parse(JSON.stringify(fields)))
      })
    }
    //涨停榜
    //https://flash-api.xuangubao.cn/api/surge_stock/stocks?normal=true&uplimit=true
    function getLimitUp() {
      let filter = $('#dropdownMenuButton1').text();
      $.get('https://flash-api.xuangubao.cn/api/pool/detail?pool_name=limit_up', function (res, status) {
        let result = $.grep(res.data, function (b) {
          $('#limitUpCount').text('涨停数量：' + res.data.length)
          //过滤st "stock_type": 1
          if (filter == '只看首板') {
            return b.stock_type != 1 && b.limit_up_days == 1
          } else if (filter == '不看首板') {
            return b.stock_type != 1 && b.limit_up_days > 1
          }
          return b.stock_type != 1
        });
        result = result.sort(compare("last_limit_up"));
        $("#J_TbData1").empty();
        for (var i = 0; i < result.length; i++) {
          //动态创建一个tr行标签,并且转换成jQuery对象
          var $trTemp = $("<tr></tr>");

          //往行里面追加 td单元格
          $trTemp.append("<td>" + (result.length - i) + "</td>");
          $trTemp.append("<td style='cursor:pointer' class='text-primary' onclick=\"forwordGu('" + result[i]
            .symbol + "')\"\>" + result[i].stock_chi_name + "\t" + result[i].symbol + "</td>");

          if (result[i].surge_reason != null) {
            $trTemp.append("<td class='text-primary' style='cursor:pointer' onclick=\"forwordBk('" + result[i]
              .surge_reason.related_plates[0].plate_id + "')\"\>" + result[i].surge_reason.related_plates[0]
              .plate_name +
              "</td>");
            $trTemp.append("<td>" + result[i].surge_reason.stock_reason + "</td>");
          } else {
            $trTemp.append("<td ></td><td ></td>");
          }
          $trTemp.append("<td>" + (result[i].buy_lock_volume_ratio * 100).toFixed(2) + "</td>");
          $trTemp.append("<td>" + (result[i].turnover_ratio * 100).toFixed(2) + "</td>");

          $trTemp.append("<td>" + formatDateTime(result[i].first_limit_up) + "</td>");
          $trTemp.append("<td>" + formatDateTime(result[i].last_limit_up) + "</td>");
          $trTemp.append("<td>" + result[i].break_limit_up_times + "</td>");
          $trTemp.append("<td>" + result[i].limit_up_days + "</td>");

          $trTemp.appendTo("#J_TbData1");
        }
      });
    }

    //格式化时间戳
    function formatDateTime(UnixTime) {
      if (UnixTime == 0) return ''
      var date = new Date(UnixTime * 1000);
      var h = date.getHours();
      h = h < 10 ? ('0' + h) : h;
      var minute = date.getMinutes();
      var second = date.getSeconds();
      minute = minute < 10 ? ('0' + minute) : minute;
      second = second < 10 ? ('0' + second) : second;
      return h + ':' + minute + ':' + second;
    };

    function getYiDong() {
      //10005逼近涨停 10003 打开涨停 10007即将打开涨停  10001 封涨停  11000板块拉升 11001板块跳水
      $.get('https://flash-api.xuangubao.cn/api/event/history?count=30&types=10001,10005,10003,10007,11000,11001',
        function (res, status) {
          let result = res.data;
          for (var i = 0; i < result.length; i++) {
            let tmp = result[i];
            let type = '';
            if (tmp.event_type == 10005) {
              type = '逼近涨停'
            } else if (tmp.event_type == 10003) {
              type = '打开涨停'
            } else if (tmp.event_type == 10007) {
              type = '即将打开涨停'
            } else if (tmp.event_type == 10001) {
              type = '封涨停'
            } else if (tmp.event_type == 11000) {
              type = '板块拉升'
            } else if (tmp.event_type == 11001) {
              type = '板块跳水'
            }

            if (tmp.stock_abnormal_event_data.name) {
              console.log(tmp.stock_abnormal_event_data.name, type, tmp.good_or_bad)
              $('#yidongData').append('<p>' + tmp.stock_abnormal_event_data.name + '</p>');
            } else {
              console.log(tmp.plate_abnormal_event_data.plate_name, type, tmp.good_or_bad)
              $('#yidongData').append('<p>' + tmp.plate_abnormal_event_data.plate_name + '</p>');
            }

          }
        });
    }
    //板块详情
    function getDetail(stock, txt) {
      $('#bkTxt').html(txt)
      $('#bankuaiData').html(
        '<div class="text-center"><div class="spinner-border text-primary" role="status"></div></div>');
      $.get('https://flash-api.xuangubao.cn/api/stage2/plates_by_stock?fields=core_avg_pcp,plate_name&symbol=' +
        stock,
        function (res, status) {
          let result = res.data;
          $('#bankuaiData').empty();
          for (var prop in result) {
            let color1 = result[prop].core_avg_pcp > 0 ? "list-group-item-danger" : "list-group-item-success";
            let color2 = result[prop].core_avg_pcp > 0 ? "bg-danger" : "bg-success";
            let str = '<li style="cursor:pointer" onclick=\'forwordBk("' + result[prop].plate_id +
              '")\' class="list-group-item d-flex ' + color1 +
              ' justify-content-between align-items-center">' + result[prop].plate_name +
              '<span class="badge ' + color2 + ' rounded-pill">' + (result[prop].core_avg_pcp * 100).toFixed(2) +
              '%</span></li>'
            $('#bankuaiData').append(str);
          }
        });
    }

    function getZhiShu() {
      $.get(
        'https://api-ddc-wscn.xuangubao.cn/market/real?fields=prod_name,last_px,px_change,px_change_rate,symbol&prod_code=000001.SS,399001.SZ,399006.SZ',
        function (res, status) {
          let result = res.data.snapshot;
          $("#zhishu").empty();
          for (var prop in result) {
            let a = result[prop];
            let color = a[2] > 0 ? "text-danger" : "text-success";
            let str = '<div style="cursor:pointer" onclick=\'forwordZhi("' + a[4] +
              '")\'><h6 class="' + color + '">' + a[0] + '\t' + a[1].toFixed(2) + '\t' + a[3].toFixed(2) +
              '%</h6></div>';
            $("#zhishu").append(str);
          }
        });
    }
    /**
     * @ function：合并指定表格列（表格id为table_id）指定列（列数为table_colnum）的相同文本的相邻单元格
     * @ param：table_id 为需要进行合并单元格的表格的id。如在HTMl中指定表格 id="data" ，此参数应为 #data 
     * @ param：table_colnum 为需要合并单元格的所在列。为数字，从最左边第一列为1开始算起。
     */
    function table_rowspan(table_id, table_colnum) {
      table_firsttd = "";
      table_currenttd = "";
      table_SpanNum = 0;
      table_Obj = $(table_id + " tr td:nth-child(" + table_colnum + ")");

      table_Obj.each(function (i) {
        if (i == 0) {
          table_firsttd = $(this);
          table_SpanNum = 1;
        } else {
          table_currenttd = $(this);
          if (table_firsttd.text() == table_currenttd.text()) { //这边注意不是val（）属性，而是text（）属性
            //td内容为空的不合并
            if (table_firsttd.text() != "") {
              table_SpanNum++;
              table_currenttd.hide(); //remove();
              table_firsttd.attr("rowSpan", table_SpanNum);
            }
          } else {
            table_firsttd = $(this);
            table_SpanNum = 1;
          }
        }
      });
    }
  </script>
</head>

<body>
  <div class="container-fluid vstack gap-2">
    <div class="row mt-2">
      <div class="col-7 d-flex justify-content-between mt-2" id="zhishu"></div>
      <div class="col-2 d-flex justify-content-between mt-2" id="redu"></div>
      <div class="col-2 d-flex justify-content-between mt-2" id="zhaban"></div>
      <div class="col-1 dropdown">
        <button class="btn btn-primary btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown"
          aria-expanded="false">
          导航
        </button>
        <ul class="dropdown-menu">
          <li><a class="dropdown-item" target="_blank" href="https://xuangubao.cn/subject/08">复盘</a></li>
          <li><a class="dropdown-item" target="_blank" href="https://xuangubao.cn/subject/02">龙虎榜</a></li>
          <li><a class="dropdown-item" target="_blank" href="https://xuangubao.cn/theme/17428174">强势股</a></li>
          <li><a class="dropdown-item" target="_blank" href="https://xuangubao.cn/live">盘中异动</a></li>
          <li><a class="dropdown-item" target="_blank" href="https://xuangubao.cn/subject/01">早晚报</a></li>
        </ul>
      </div>
    </div>
    <div class="row ">
      <div class="col d-flex justify-content-between" id="topdata"></div>
    </div>
    <div class="row">
      <div class="col-6">
        <table class="table table-hover table-sm">
          <thead>
            <tr>
              <th><span class="text-primary" id="timer"></span> 板块</th>
              <th>详情</th>
              <th>量比<select class="form-select-sm select" cl id="lbSelect">
                  <option value="0">0</option>
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3" selected>3</option>

                </select></th>
              <th>涨速<select class="form-select-sm select" id="zsSelect">
                  <option value="0">0</option>
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3" selected>3</option>
                </select></th>
              <th>换手<select class="form-select-sm select" id="hsSelect">
                  <option value="0">0</option>
                  <option value="2" selected>2</option>
                </select></th>
              <th>涨幅</th>
              <th>首次涨停时间</th>
              <th>涨停天数</th>
              <th>开板次数</th>
            </tr>
          </thead>
          <tbody id="J_TbData">
          </tbody>
        </table>
      </div>
      <div class="col-2">
        <p class="text-center text-danger" id="bkTxt">
          所属板块
        </p>
        <ul class="list-group" id="bankuaiData"></ul>
      </div>
      <div class="col-4">
        <table class="table table-hover table-sm">
          <thead>
            <tr>
              <th>连板数</th>
              <th>板块</th>
              <th>股票</th>
              <th>涨幅</th>
            </tr>
          </thead>
          <tbody id="yesterdayLimitUp">
          </tbody>
        </table>
      </div>
    </div>

    <div class=" justify-content-between d-flex ">
      <div id="limitUpCount" class=" text-danger"></div>
      <div class=" dropdown">
        <button class="btn btn-primary btn-sm dropdown-toggle" type="button" id="dropdownMenuButton1"
          data-bs-toggle="dropdown" aria-expanded="false">
          全部
        </button>
        <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1" id="dropdownMenu">
          <li><a class="dropdown-item" href="#">全部</a></li>
          <li><a class="dropdown-item" href="#">只看首板</a></li>
          <li><a class="dropdown-item" href="#">不看首板</a></li>
        </ul>
      </div>

    </div>
    <table class="table table-hover table-sm">
      <thead>
        <tr>
          <th>NO.</th>
          <th>股票</th>
          <th nowrap="nowrap">板块</th>
          <th>理由分析</th>
          <th nowrap="nowrap">封单比</th>
          <th nowrap="nowrap">换手率</th>
          <th>首次封板</th>
          <th>最后封板</th>
          <th nowrap="nowrap">开板</th>
          <th nowrap="nowrap">连板</th>
        </tr>
      </thead>
      <tbody id="J_TbData1">
      </tbody>
    </table>
  </div>
</body>

</html>